package com.lagou.user.controller;

import com.lagou.edu.service.CodeService;
import com.lagou.user.entity.Token;
import com.lagou.user.mapper.TokenMapper;
import com.lagou.user.util.JwtUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private TokenMapper tokenMapper;

    /*@Autowired
    private CodeFeignClient codeFeignClient;*/

    @Reference
    private CodeService codeService;

    @GetMapping("/register/{email}/{password}/{code}")
    public Integer register(@PathVariable("email") String email, @PathVariable("password") String password,
                            @PathVariable("code") String code) {

        Token isRegistered = tokenMapper.findByEmail(email);
        if(isRegistered != null) {
            return 3;//该邮箱已注册
        }

//        Integer validateResult = codeFeignClient.validateCode(email, code);
        Integer validateResult = codeService.validateCode(email, code);
        if(validateResult == 0) {
            String content = email + password;
            String token = JwtUtil.createToken(content);
            tokenMapper.add(email, token);
        }

        return validateResult;
    }

    @GetMapping("/isRegistered/{email}")
    public boolean isRegistered(@PathVariable("email") String email) {
        Token byEmail = tokenMapper.findByEmail(email);
        return byEmail != null;
    }

    @GetMapping("/login/{email}/{password}")
    public String login(@PathVariable("email") String email, @PathVariable("password") String password,
                        HttpServletResponse response) {
        String content = email + password;
        String token = JwtUtil.createToken(content);
        Token result = tokenMapper.findByToken(token);

        if(result != null) {
            Cookie cookie = new Cookie("token", token);
            cookie.setPath("/");
            response.addCookie(cookie);
            return email;
        } else {
            return null;
        }
    }

    @GetMapping("/info/{token}")
    public String queryEmailByToken(@PathVariable("token") String token) {
        Token byToken = tokenMapper.findByToken(token);
        return byToken != null ? byToken.getEmail() : null;
    }
}
